// Package config
package config

import (
	"encoding/json"
	"io/ioutil"
)

//
type Config struct {
	cfg map[string]interface{}
}

// 获取string类型的值
func (this *Config) GetValue(key string) string {
	var result = ""

	if value, ok := this.cfg[key]; ok {
		switch value.(type) {
		case string:
			result = value.(string)
		}
	}

	return result
}

// 获取int类型的值
func (this *Config) GetIntValue(key string) int {
	var result = 0

	if value, ok := this.cfg[key]; ok {
		switch value.(type) {
		case float64:
			result = int(value.(float64))
		}
	}

	return result
}

// 获取bool类型的值
func (this *Config) GetBoolValue(key string) bool {
	var result = false

	if value, ok := this.cfg[key]; ok {
		switch value.(type) {
		case bool:
			result = value.(bool)
		}
	}

	return result
}

// 加载配置文件
func LoadConfigFile(fileName string) (*Config, error) {
	bytes, err := readFile(fileName)
	if err != nil {
		return nil, err
	}

	var result map[string]interface{}
	result, err = jsonToMap(bytes)
	if err != nil {
		return nil, err
	}

	return &Config{cfg: result}, nil
}

//func Reload() (*Config, error) {
//}

func readFile(fileName string) ([]byte, error) {
	bytes, err := ioutil.ReadFile(fileName)
	if err != nil {
		// log.Fatalf("Fail to read file: %v\n", err)
		return nil, err
	}

	return bytes, nil
}

func jsonToMap(bytes []byte) (map[string]interface{}, error) {
	var result map[string]interface{}

	if err := json.Unmarshal(bytes, &result); err != nil {
		return nil, err
	}

	return result, nil
}
